<template>
  <div class="custom-card" @dblclick="openEditor">
    <!-- 标题 -->
    <div>
      <n-flex>
        <n-icon size="16" class="icon" style="top: 3px;">
          <DocumentTextOutline />
        </n-icon>
        <!-- 不使用模板插值来直接渲染到 contenteditable 元素 -->
        <div
        class="card-title"
        contenteditable="true"
        spellcheck="false"
        ref="titleRef"
        @blur="onTitleBlur"
        @input="onTitleInput">
        </div>
      </n-flex>

    </div>

    <div class="divider"></div>

    <!-- 内容 -->
    <div
      class="card-content"
      ref="contentRef"
      contenteditable="true"
      spellcheck="false"
      @blur="onContentBlur"
      @input="onContentInput"
      style="height: 130px;"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { NIcon } from 'naive-ui'
import { DocumentTextOutline } from '@vicons/ionicons5'
import { invoke } from '@tauri-apps/api/core'
import { useWindow } from '../../hooks/useWindow.ts'
const { createWebviewWindow } = useWindow()

interface TreeNodeData {
  key: string | number
  parentKey: string | number
  groupId: string | number
  type: string
  label: string
  heading?: string
  content?: string
  isFolder: number
  children: TreeNodeData[]
}

const props = defineProps<{
  node: TreeNodeData
}>()

const emit = defineEmits<{
    upTextLabel: [key: string|number, lable: string]
  }>()

// 如果希望向外 emit 更安全可控的更新，可以打开下行
// const emit = defineEmits(['update:node', 'change'])

/* -------------------------
   本地响应式状态（用于显示 / 编辑）
   ------------------------- */
const title = ref(props.node?.label ?? '')
const content = ref(props.node?.heading ?? '')

const titleRef = ref<HTMLElement | null>(null)
const contentRef = ref<HTMLElement | null>(null)

/* -------------------------
   当 props.node 变化时同步到本地，并更新 DOM
   ------------------------- */
watch(
  () => props.node,
  (v) => {
    refreshNodes(v)
  },
  { deep: true, immediate: true }
)

function refreshNodes(v: TreeNodeData | undefined) {
  if (!v) return
  title.value = v.label ?? ''
  content.value = v.heading ?? ''
  // 把值写入 DOM（避免模板插值导致 Vue 管理该节点）
  nextTick(() => {
    if (titleRef.value) titleRef.value.textContent = title.value
    if (contentRef.value) contentRef.value.textContent = content.value
  })
}

/* -------------------------
   初始化（mounted）
   ------------------------- */
onMounted(() => {
  if (titleRef.value) titleRef.value.textContent = title.value
  if (contentRef.value) contentRef.value.textContent = content.value
})

/* -------------------------
   用户编辑事件（实时或失焦时同步）
   - 我们同时在 input 时更新本地状态，blur 时写回 props.node（或 emit）
   ------------------------- */
function onTitleInput(e: InputEvent) {
  const t = (e.target as HTMLElement).textContent ?? ''
  title.value = t
}

function onContentInput(e: InputEvent) {
  const t = (e.target as HTMLElement).textContent ?? ''
  content.value = t
}

async function onTitleBlur(e: Event) {
  const t = (e.target as HTMLElement).textContent?.trim() ?? ''
  title.value = t
  // 写回 props.node（如果你不想直接修改 prop，可以 emit 给父组件）
  if (props.node) props.node.label = t
  await updateNode()
  
  emit('upTextLabel', props.node.key, props.node.label)
}

async function onContentBlur(e: Event) {
  const t = (e.target as HTMLElement).textContent?.trim() ?? ''
  content.value = t
  if (props.node) props.node.heading = t
  await updateNode()
  // emit('update:node', { ...props.node, content: t })
}

async function updateNode() {
  await invoke("update_momento_title_heading", { 
    id: props.node.key.toString(), 
    title: props.node.label, 
    heading: props.node.heading ?? "",
    });
}

async function openEditor() {
  await createWebviewWindow('文本编辑-text', 'editor-'+props.node.key, 'editor', 960, 720, undefined, true, undefined, 480, false, false);
}

</script>

<style scoped>
.custom-card {
  width: 200px;
  background-color: #fdf8f4;
  border: 1px solid #d7d1cb;
  border-radius: 8px;
  padding: 6px 10px;
  box-shadow: 0 0 0 2px #f0ece9 inset;
  transition: box-shadow 0.2s ease;
}

.custom-card:hover {
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.08);
}

.card-title {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: bold;
  font-size: 14px;
  color: #222;
  user-select: text;
  outline: none;
  cursor: text;
  min-height: 20px;
}

.icon {
  flex-shrink: 0;
  color: #555;
}

.divider {
  border-top: 1px solid #e3dfdc;
  margin: 4px 0;
}

.card-content {
  font-size: 13px;
  color: #333;
  min-height: 40px;
  outline: none;
  white-space: pre-wrap;
  line-height: 1.5;
  cursor: text;
  overflow: auto;
  word-break: break-word;
}
</style>
